/*
 * classe dedicata alla connessione al sito per la verifica delle credenziali
 * inoltre rende disponibile il nome e la matricola dell'utente.
 */
package tools;

import java.io.*;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;

/**
 *
 * @author Marco Jerome Gasparrini
 *
 *
 */
public class SecureConnector {

    private String User;
    private String Password;
    private String Name;
    private String Mat;
    private boolean success = false;
    private String Checkword = "amn";
    private String SCheckword = "";
    private final String https_url = "https://zagomattia.it/receiver.php";

   
    public SecureConnector(String user, String pass) {


        // controllo SQL INJECTION
        user = user.replaceAll("=", "").replaceAll("'", "").trim().toLowerCase();
        if (user.toCharArray().length != 8) {
            user = "";
        }
        pass = pass.replaceAll("=", "").replaceAll("'", "").replaceAll(" ", "").trim();
        if (pass.toCharArray().length > 10) {
            pass = "";
        }

        this.User = user;
        this.Password = pass;


        this.Checkword += new BigInteger(130, new SecureRandom()).toString(32);

        URL url;
        try {

            //Creo la richiesta esatta con i paramentri passati, senza usare i metodi perchè non funzionano 
            //con questo tipo di soluzione. Ho messo più concatenazioni per maggiore chiarezza.

            String first_query = "?"
                + "user" + "=" + URLEncoder.encode(User, "UTF8")
                + "&"
                + "checkword" + "=" + URLEncoder.encode(Checkword, "UTF8");

            url = new URL(https_url + first_query);

            HttpsURLConnection con1 = (HttpsURLConnection) url.openConnection();

            validation(con1);

            this.Checkword += new BigInteger(130, new SecureRandom()).toString(32);
            
            String second_query = "?"
                + "user" + "=" + URLEncoder.encode(User, "UTF8")
                + "&"
                + "pass" + "=" + URLEncoder.encode(Password, "UTF8")
                + "&"
                + "checkword" + "=" + URLEncoder.encode(Checkword, "UTF8")
                + "&"
                + "Scheckword" + "=" + URLEncoder.encode(SCheckword, "UTF8");

            url = new URL(https_url + second_query);

            HttpsURLConnection con2 = (HttpsURLConnection) url.openConnection();

            //stampo certificato, commentata per debug
            //print_https_cert(con);

            response_processor(con2);

        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

    }

    private void print_https_cert(HttpsURLConnection con) {

        if (con != null) {

            try {


                // Dati certificato
                System.out.println("Response Code : " + con.getResponseCode());
                System.out.println("Cipher Suite : " + con.getCipherSuite());
                System.out.println("\n");

                Certificate[] certs = con.getServerCertificates();
                for (Certificate cert : certs) {
                    System.out.println("Cert Type : " + cert.getType());
                    System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                    System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                    System.out.println("\n");
                }

            } catch (SSLPeerUnverifiedException e) {
            } catch (IOException e) {
            }

        }

    }

    private void validation(HttpsURLConnection con) {
        if (con != null) {

            System.out.println("===== VALIDATION =====");
            try {
                BufferedReader br =
                    new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
                String input;
                String tmp_check = "",tmp_scheck = "";
                while ((input = br.readLine()) != null) {
                    if(input.contains("@")){
                       input = input.replace("@", "");
                        char[] temp = input.toCharArray();
                        boolean check_ok = false;

                        for (int i = 0; i < temp.length; i++) {
                            if (!check_ok) {
                                if (temp[i] == '-') {
                                    check_ok = true;
                                    i++;
                                }
                                tmp_scheck += temp[i];

                            } else {
                                tmp_check += temp[i];
                            }
                        }
                        
                        
                        tmp_check = tmp_check.trim();
                        System.out.println(tmp_scheck.trim());
                        if(tmp_check.equals(this.Checkword)){
                            this.SCheckword = tmp_scheck.trim();
                            System.out.println("VALIDATION SUCCESFUL!");
                        }
                    }
                }
                
            } catch (IOException ex) {
                Logger.getLogger(SecureConnector.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void response_processor(HttpsURLConnection con) {
        if (con != null) {

            try {

                System.out.println("====== RESPONSE ======");
                BufferedReader br =
                    new BufferedReader(
                    new InputStreamReader(con.getInputStream()));

                String input;
                String tmp_name = "", tmp_mat = "", tmp_ckw = "";

                while ((input = br.readLine()) != null) {
                    //System.out.println(input);
                    if (input.contains("#")) {

                        input = input.replace("#", "");
                        char[] temp = input.toCharArray();
                        boolean mat_ok = false;

                        for (int i = 0; i < temp.length; i++) {
                            if (!mat_ok) {
                                if (temp[i] == '-') {
                                    mat_ok = true;
                                    i++;
                                }
                                tmp_name += temp[i];

                            } else {
                                tmp_mat += temp[i];
                            }
                        }
                        tmp_name = tmp_name.trim();
                        tmp_mat = tmp_mat.trim();
                        System.out.println(tmp_name + " - " + tmp_mat);
                    }
                    if (input.contains("@")) {
                        input = input.replace("@", "");
                        tmp_ckw = input.trim();
                        System.out.println("CheckWord = " + tmp_ckw);
                    }
                }
                br.close();

                if (tmp_name != "" && tmp_mat != "" && tmp_ckw.equals(this.Checkword.substring(3))) {
                    this.Name = tmp_name;
                    this.Mat = tmp_mat;
                    this.success = true;
                    System.out.println("SUCCESS!");
                } else {
                    System.out.println("ACESS DENIED!");
                }


            } catch (IOException e) {
            }

        }

    }

    public String getName() {
        return Name;
    }

    public String getMat() {
        return Mat;
    }

    public boolean isSuccess() {
        return success;
    }
}